<!--
 * Copyright © 2025 上海火金网络科技有限公司. All rights reserved.
 * Service Provider Channel Config Modal - 服务商渠道配置模态框
 *
 * 功能：服务商模式下的渠道配置管理，支持Protocol3动态协议
 * 版本：2.0.0 - 移除兼容性包袱，只支持Protocol3
 *
 * Website: https://www.anypay.com
-->

<template>
  <a-modal
    :open="visible"
    :title="`${provider?.providerName} - 支付渠道配置`"
    width="95%"
    :footer="null"
    @cancel="handleClose"
    @update:open="$emit('update:visible', $event)"
    class="channel-config-modal"
  >
    <div class="channel-config-workspace">
      <!-- 左侧渠道列表 -->
      <div class="channel-sidebar">
        <div class="sidebar-header">
          <h3>支付渠道</h3>
        </div>

        <div class="channel-list">
          <div
            v-for="template in sortedChannelTemplates"
            :key="template.channelId"
            class="channel-item"
            :class="{
              'active': state.selectedChannelId === template.channelId,
              'configured': template.isConfigured
            }"
            @click="handleChannelSelect(template.channelId)"
          >
            <div class="channel-item-content">
              <div class="channel-basic">
                <img :src="template.iconUrl" :alt="template.channelName" class="channel-icon" />
                <div class="channel-info">
                  <div class="channel-name">{{ template.channelName }}</div>
                </div>
              </div>
              <div class="channel-status">
                <div style="display: flex; flex-direction: column; gap: 4px; align-items: flex-end;">
                  <a-tag v-if="template.isConfigured" color="success" size="small">
                    已配置
                  </a-tag>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧配置详情 -->
      <div class="channel-detail">
        <div v-if="state.loading && !state.initialized" class="loading-state">
          <a-skeleton active :paragraph="{ rows: 8 }" />
        </div>

        <div v-else-if="!state.selectedChannelId" class="empty-state">
          <a-empty description="请选择要配置的渠道" />
        </div>

        <div v-else class="channel-detail-content">
          <div class="detail-header">
            <div class="channel-title">
              <img :src="selectedChannelTemplate?.iconUrl" :alt="selectedChannelTemplate?.channelName" class="channel-icon" />
              <div>
                <h3>{{ selectedChannelTemplate?.channelName }}</h3>
                <p class="channel-desc">{{ selectedChannelTemplate?.description }}</p>
              </div>
            </div>

            <div class="detail-actions">
              <!-- 控制开关组 -->
              <div style="display: flex; gap: 16px; align-items: center;">
                <!-- Protocol3模式显示 -->
                <div class="mode-switch-control" style="display: flex; align-items: center;">
                  <span style="color: #666; font-size: 13px; margin-right: 8px;">配置模式：</span>
                  <a-tag color="blue" size="small">
                    Protocol3
                  </a-tag>
                  <span style="color: #666; font-size: 12px; margin-left: 8px;">
                    动态协议
                  </span>
                </div>

                <!-- 启用状态开关 -->
                <div class="channel-status-control" style="display: flex; align-items: center;">
                  <span style="color: #666; font-size: 13px; margin-right: 8px;">启用状态：</span>
                  <a-switch
                    :checked="selectedChannelConfig?.enabled || false"
                    @change="handleChannelToggle(state.selectedChannelId, $event)"
                    size="small"
                  />
                  <span style="color: #666; font-size: 12px; margin-left: 8px;">
                    {{ selectedChannelConfig?.enabled ? '已启用' : '已禁用' }}
                  </span>
                </div>
              </div>
            </div>
          </div>

          <!-- 配置表单 - Protocol3 Tab界面 -->
          <div class="config-form-container">
            <!-- Protocol3协议信息显示 -->
            <div style="margin-bottom: 16px; padding: 12px 16px; background: #fafafa; border: 1px solid #e8e8e8; border-radius: 6px;">
              <div style="display: flex; align-items: center; gap: 8px;">
                <span style="color: #666; font-size: 13px;">📋 当前协议：</span>
                <span style="color: #1890ff; font-weight: 500; font-size: 13px;">{{ currentProtocolId }}</span>
                <span
                  v-if="protocolInfo?.isDefault"
                  style="color: #722ed1; font-size: 12px; background: #f9f0ff; padding: 2px 6px; border-radius: 4px; border: 1px solid #d3adf7;"
                >
                  兜底协议
                </span>
                <span
                  v-if="protocolInfo?.source === 'protocol3'"
                  style="color: #1890ff; font-size: 12px; background: #e6f7ff; padding: 2px 6px; border-radius: 4px; border: 1px solid #91d5ff;"
                >
                  Protocol3
                </span>
                <span
                  v-else-if="protocolInfo?.source === 'fallback'"
                  style="color: #722ed1; font-size: 12px; background: #f9f0ff; padding: 2px 6px; border-radius: 4px; border: 1px solid #d3adf7;"
                >
                  自动适配
                </span>
              </div>
            </div>

            <a-tabs v-model:activeKey="state.configActiveTab" type="card">
              <!-- Protocol3模式 -->
              <!-- 渲染Protocol3分区Tab -->
              <a-tab-pane
                v-for="section in configSections"
                :key="section.key"
                :tab="section.tab"
              >
                <a-form layout="vertical" :model="selectedChannelConfig || {}">
                  <!-- 渲染该分区的字段 -->
                  <a-card :title="section.tab" size="small" style="margin-bottom: 16px;">
                    <a-row :gutter="16">
                      <a-col
                        v-for="field in section.fields"
                        :key="field.fieldKey"
                        :span="getFieldSpan(field.fieldType)"
                      >
                        <a-form-item
                          :label="field.fieldName"
                          :required="field.required"
                          :help="field.description || field.placeholder"
                        >
                          <!-- 输入框 -->
                          <a-input
                            v-if="field.fieldType === 'INPUT'"
                            :value="getFieldValue(field.fieldKey, section.key)"
                            @update:value="setFieldValue(field.fieldKey, section.key, $event)"
                            :placeholder="field.placeholder"
                          />
                          <!-- 密码框 -->
                          <a-input-password
                            v-else-if="field.fieldType === 'PASSWORD'"
                            :value="getFieldValue(field.fieldKey, section.key)"
                            @update:value="setFieldValue(field.fieldKey, section.key, $event)"
                            :placeholder="field.placeholder"
                          />
                          <!-- 选择框 -->
                          <a-select
                            v-else-if="field.fieldType === 'SELECT'"
                            :value="getFieldValue(field.fieldKey, section.key)"
                            @update:value="setFieldValue(field.fieldKey, section.key, $event)"
                            :placeholder="field.placeholder"
                          >
                            <a-select-option
                              v-for="option in field.options"
                              :key="option.value"
                              :value="option.value"
                            >
                              {{ option.label }}
                            </a-select-option>
                          </a-select>
                          <!-- 文本域 -->
                          <a-textarea
                            v-else-if="field.fieldType === 'TEXTAREA'"
                            :value="getFieldValue(field.fieldKey, section.key)"
                            @update:value="setFieldValue(field.fieldKey, section.key, $event)"
                            :placeholder="field.placeholder"
                            :rows="4"
                          />
                          <!-- URL输入框 -->
                          <a-input
                            v-else-if="field.fieldType === 'URL'"
                            :value="getFieldValue(field.fieldKey, section.key)"
                            @update:value="setFieldValue(field.fieldKey, section.key, $event)"
                            :placeholder="field.placeholder"
                          />
                          <!-- 文件上传 -->
                          <a-upload
                            v-else-if="field.fieldType === 'UPLOAD'"
                            :before-upload="() => false"
                            :file-list="[]"
                            @change="(info: any) => handleFileUpload(field.fieldKey, section.key, info)"
                          >
                            <a-button>
                              <template #icon>
                                <UploadOutlined />
                              </template>
                              选择文件
                            </a-button>
                            <div class="upload-tip">{{ field.placeholder }}</div>
                          </a-upload>
                          <!-- URL输入框 -->
                          <a-input
                            v-else-if="field.fieldType === 'URL'"
                            :value="getFieldValue(field.fieldKey, section.key)"
                            @update:value="setFieldValue(field.fieldKey, section.key, $event)"
                            :placeholder="field.placeholder"
                          />
                          <!-- 数字输入框 -->
                          <a-input-number
                            v-else-if="field.fieldType === 'NUMBER'"
                            :value="getFieldValue(field.fieldKey, section.key)"
                            @update:value="setFieldValue(field.fieldKey, section.key, $event)"
                            :placeholder="field.placeholder"
                            style="width: 100%"
                          />
                          <!-- 开关 -->
                          <a-switch
                            v-else-if="field.fieldType === 'SWITCH'"
                            :checked="getFieldValue(field.fieldKey, section.key)"
                            @update:checked="setFieldValue(field.fieldKey, section.key, $event)"
                          />
                          <!-- 单选框 -->
                          <a-radio-group
                            v-else-if="field.fieldType === 'RADIO'"
                            :value="getFieldValue(field.fieldKey, section.key)"
                            @update:value="setFieldValue(field.fieldKey, section.key, $event)"
                          >
                            <a-radio
                              v-for="option in (field.options || [])"
                              :key="option.value"
                              :value="option.value"
                            >
                              {{ option.label }}
                            </a-radio>
                          </a-radio-group>
                          <!-- 多选框 -->
                          <a-checkbox-group
                            v-else-if="field.fieldType === 'CHECKBOX'"
                            :value="getFieldValue(field.fieldKey, section.key)"
                            @update:value="setFieldValue(field.fieldKey, section.key, $event)"
                          >
                            <a-checkbox
                              v-for="option in (field.options || [])"
                              :key="option.value"
                              :value="option.value"
                            >
                              {{ option.label }}
                            </a-checkbox>
                          </a-checkbox-group>
                          <!-- 邮箱输入框 -->
                          <a-input
                            v-else-if="field.fieldType === 'EMAIL'"
                            :value="getFieldValue(field.fieldKey, section.key)"
                            @update:value="setFieldValue(field.fieldKey, section.key, $event)"
                            :placeholder="field.placeholder"
                            type="email"
                          />
                          <!-- 日期选择器 -->
                          <a-date-picker
                            v-else-if="field.fieldType === 'DATE'"
                            :value="getFieldValue(field.fieldKey, section.key)"
                            @update:value="setFieldValue(field.fieldKey, section.key, $event)"
                            :placeholder="field.placeholder"
                            style="width: 100%"
                          />
                          <!-- 日期时间选择器 -->
                          <a-date-picker
                            v-else-if="field.fieldType === 'DATETIME'"
                            :value="getFieldValue(field.fieldKey, section.key)"
                            @update:value="setFieldValue(field.fieldKey, section.key, $event)"
                            :placeholder="field.placeholder"
                            show-time
                            style="width: 100%"
                          />
                          <!-- JSON编辑器 -->
                          <a-textarea
                            v-else-if="field.fieldType === 'JSON'"
                            :value="getFieldValue(field.fieldKey, section.key)"
                            @update:value="setFieldValue(field.fieldKey, section.key, $event)"
                            :placeholder="field.placeholder || '请输入JSON格式数据'"
                            :rows="6"
                          />
                        </a-form-item>
                      </a-col>
                    </a-row>
                  </a-card>
                </a-form>
              </a-tab-pane>
            </a-tabs>
          </div>

          <!-- 固定保存按钮 -->
          <div class="fixed-save-button">
            <a-button
              type="primary"
              size="large"
              @click="handleSaveChannelConfig(state.selectedChannelId)"
              :loading="state.savingChannels.includes(state.selectedChannelId)"
            >
              <template #icon>
                <SaveOutlined />
              </template>
              保存配置
            </a-button>
          </div>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { reactive, computed, watch, ref } from 'vue'
import { message } from 'ant-design-vue'
import { UploadOutlined, SaveOutlined } from '@ant-design/icons-vue'
import {
  getAllConfigurableChannels,
  type ServiceProvider
} from '@/mock/service-providers'
import { protocol3Manager } from '@/mock/protocol3-manager'
import { initializeSampleData } from '@/mock/protocol3-sample-data'
import { serviceProviderProtocolAdapter } from './protocol-adapter'
import {
  getProviderChannelConfigs,
  saveProviderChannelConfig,
  updateChannelStatus,
  type ServiceProviderChannelConfigData
} from './api/channel-config-api'

// Props
interface Props {
  visible: boolean
  provider?: ServiceProvider | null
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  provider: null
})

// Emits
const emit = defineEmits<{
  'update:visible': [visible: boolean]
  'success': []
}>()

// 渠道模板接口定义（简化版，只保留Protocol3需要的字段）
interface ChannelTemplate {
  channelId: string
  channelName: string
  channelCode: string
  iconUrl: string
  description: string
}

// 服务商渠道配置接口定义（更新为统一渠道配置结构）
interface ServiceProviderChannelConfig {
  configId: string
  providerId: string
  channelId: string
  channelCode: string
  channelName: string
  enabled: boolean
  configData: Record<string, any>
  status: 'ACTIVE' | 'INACTIVE'
  createdTime: string
  updatedTime: string
}

// 🔧 重构版本 - 核心状态管理
// 解决数据串问题的关键：使用双键存储和严格的状态隔离
const state = reactive({
  // 🔑 关键：当前服务商ID，用于数据隔离
  currentProviderId: '',

  // 渠道模板（全局共享，不会串）
  channelTemplates: [] as ChannelTemplate[],

  // 🔑 关键：使用Map存储，按服务商ID隔离数据
  providerChannelConfigsMap: new Map<string, ServiceProviderChannelConfig[]>(),

  // 协议缓存 - 使用协议适配器获取的协议数据
  protocolCache: new Map<string, any>(),

  // 当前选中状态
  selectedChannelId: '',
  configActiveTab: '',

  // 加载状态
  loading: false,
  initialized: false,
  protocol3Ready: false,

  // 保存状态
  savingChannels: [] as string[],

  // 🔧 新增：错误状态管理
  error: null as string | null,

  // 🔧 新增：数据版本，用于强制刷新
  dataVersion: 0
})

// 🔧 重构版本 - 计算属性
// 支持数据隔离和严格的状态管理

const selectedChannelTemplate = computed(() => {
  return state.channelTemplates.find(t => t.channelId === state.selectedChannelId)
})

// 带配置状态和排序的渠道模板
const sortedChannelTemplates = computed(() => {
  // 为每个渠道模板添加配置状态信息
  const templatesWithStatus = state.channelTemplates.map(template => {
    // 检查该渠道是否已配置（基于当前服务商的配置数据）
    const isConfigured = currentProviderChannelConfigs.value.some(config =>
      config.channelId === template.channelId &&
      config.configData &&
      Object.keys(config.configData).length > 0
    )

    return {
      ...template,
      isConfigured
    }
  })

  // 排序：已配置的渠道优先，然后按渠道名称排序
  return templatesWithStatus.sort((a, b) => {
    // 首先按配置状态排序：已配置的在前
    if (a.isConfigured && !b.isConfigured) return -1
    if (!a.isConfigured && b.isConfigured) return 1

    // 然后按渠道名称排序
    return a.channelName.localeCompare(b.channelName)
  })
})

// 🔑 关键：获取当前服务商的渠道配置（数据隔离）
const currentProviderChannelConfigs = computed(() => {
  if (!state.currentProviderId) return []
  return state.providerChannelConfigsMap.get(state.currentProviderId) || []
})

// 🔧 修复：分离数据状态和UI编辑状态
const selectedChannelConfig = computed(() => {
  if (!state.selectedChannelId) return null

  // 只从数据库加载的真实配置中查找，不创建新配置
  const realConfig = currentProviderChannelConfigs.value.find(c => c.channelId === state.selectedChannelId)

  if (realConfig) {
    return realConfig // 返回数据库中的真实配置
  }

  // 如果数据库中没有配置，返回一个UI临时对象（不添加到状态中）
  const template = state.channelTemplates.find(t => t.channelId === state.selectedChannelId)
  if (!template) return null

  return reactive({
    configId: '', // 空ID表示未保存
    providerId: state.currentProviderId,
    channelId: state.selectedChannelId,
    channelCode: template.channelCode,
    channelName: template.channelName,
    enabled: false,
    configData: {}, // 空配置
    status: 'INACTIVE',
    createdTime: '',
    updatedTime: ''
  }) as ServiceProviderChannelConfig
})

// 🔧 新增：数据完整性检查
const isDataValid = computed(() => {
  return !!(
    state.currentProviderId &&
    state.initialized &&
    state.protocol3Ready &&
    !state.error
  )
})

// 🔧 新增：当前服务商统计信息
const providerStats = computed(() => {
  const configs = currentProviderChannelConfigs.value
  return {
    total: configs.length,
    enabled: configs.filter(c => c.enabled).length,
    disabled: configs.filter(c => !c.enabled).length,
    channels: [...new Set(configs.map(c => c.channelCode))]
  }
})

// 获取并缓存协议数据的函数
const getProtocolData = async (channelCode: string) => {
  // 先检查缓存
  if (state.protocolCache.has(channelCode)) {
    return state.protocolCache.get(channelCode)
  }

  try {
    // 使用协议适配器获取协议
    const protocolInfo = await serviceProviderProtocolAdapter.getChannelProtocol(channelCode, 'PROVIDER')

    if (protocolInfo?.parsedData) {
      // 构造与原protocol3Manager兼容的数据结构
      const compatibleProtocol = {
        ...protocolInfo.parsedData,
        protocolId: protocolInfo.protocolId,
        protocolName: protocolInfo.protocol?.protocolName,
        protocolType: protocolInfo.protocol?.protocolType,
        channelCode: protocolInfo.protocol?.channelCode,
        isDefault: protocolInfo.isDefault,
        source: protocolInfo.source
      }

      // 缓存协议数据
      state.protocolCache.set(channelCode, compatibleProtocol)
      return compatibleProtocol
    }
  } catch (error) {
    console.warn(`获取协议数据失败: ${channelCode}`, error)
  }

  return null
}

// 当前选中渠道的协议数据（响应式）
const selectedChannelProtocol = ref(null)

// 监听选中渠道变化，异步加载协议数据
watch([() => state.selectedChannelId, () => state.protocol3Ready], async ([channelId, ready]) => {
  if (!channelId || !ready) {
    selectedChannelProtocol.value = null
    return
  }

  const template = selectedChannelTemplate.value
  if (!template) {
    selectedChannelProtocol.value = null
    return
  }

  try {
    // 使用协议适配器获取协议数据
    const protocol = await getProtocolData(template.channelCode)
    selectedChannelProtocol.value = protocol
  } catch (error) {
    console.warn('获取渠道协议失败:', error)
    selectedChannelProtocol.value = null
  }
}, { immediate: true })

// 获取当前协议ID - 使用协议适配器数据
const currentProtocolId = computed(() => {
  const protocol = selectedChannelProtocol.value
  return protocol?.protocolId || '未知协议'
})

// 获取协议信息（包括是否为默认协议）- 使用协议适配器数据
const protocolInfo = computed(() => {
  const protocol = selectedChannelProtocol.value
  if (!protocol) return null

  return {
    protocol: protocol,
    protocolId: protocol.protocolId,
    isDefault: protocol.isDefault,
    source: protocol.source
  }
})

// Protocol3 配置分区 - 作为tabs
const configSections = computed(() => {
  // 必须满足所有条件才能渲染配置分区
  if (!state.selectedChannelId || !state.initialized || !state.protocol3Ready) {
    return []
  }

  const protocol = selectedChannelProtocol.value
  if (!protocol?.configSections?.length) {
    return []
  }

  const sections = protocol.configSections.map((section: any) => ({
    key: section.sectionKey,
    tab: section.sectionName,
    icon: section.icon,
    description: section.description,
    fields: section.fields,
    order: section.order || 0,
    collapsed: section.collapsed || false
  })).sort((a: any, b: any) => a.order - b.order)

  return sections
})

// 统一的状态管理函数
const updateChannelState = (channelId: string) => {
  state.selectedChannelId = channelId

  // 同步更新活动tab（基于当前可用的配置分区）
  const sections = configSections.value
  if (sections.length > 0) {
    state.configActiveTab = sections[0].key
  } else {
    state.configActiveTab = ''
  }
}

// 监听配置分区变化，自动修正活动tab
watch([configSections], (newSections) => {
  // 如果当前活动tab不在新的分区列表中，则重新设置
  if (newSections.length > 0) {
    const currentTabExists = newSections.some(section => section.key === state.configActiveTab)
    if (!currentTabExists || !state.configActiveTab) {
      const newActiveTab = newSections[0].key
      state.configActiveTab = newActiveTab
    }
  } else {
    state.configActiveTab = ''
  }
}, { immediate: true })

// 🔧 重构版本 - 状态重置和管理
// 解决数据串问题的关键函数

/**
 * 完全重置状态 - 关闭模态框时使用
 */
const resetState = () => {
  Object.assign(state, {
    currentProviderId: '',
    channelTemplates: [],
    providerChannelConfigsMap: new Map(),
    selectedChannelId: '',
    configActiveTab: '',
    loading: false,
    initialized: false,
    protocol3Ready: false,
    savingChannels: [],
    error: null,
    dataVersion: 0
  })
}

/**
 * 🔑 关键函数：切换服务商时的状态重置
 * 解决数据串问题的核心机制
 */
const resetForNewProvider = (newProviderId: string) => {
  // 🔧 修复：切换服务商时重置选中状态，避免数据串
  state.currentProviderId = newProviderId
  state.selectedChannelId = ''
  state.configActiveTab = ''
  state.initialized = false
  state.error = null
  state.dataVersion++
}

/**
 * 🔑 关键函数：获取或创建服务商的渠道配置存储
 */
const getOrCreateProviderConfigs = (providerId: string): ServiceProviderChannelConfig[] => {
  if (!state.providerChannelConfigsMap.has(providerId)) {
    state.providerChannelConfigsMap.set(providerId, [])
  }
  return state.providerChannelConfigsMap.get(providerId)!
}

/**
 * 🔑 关键函数：设置服务商的渠道配置
 */
const setProviderConfigs = (providerId: string, configs: ServiceProviderChannelConfig[]) => {
  state.providerChannelConfigsMap.set(providerId, configs)
  state.dataVersion++
}

// 方法
const handleClose = () => {
  emit('update:visible', false)
  resetState()
}

const handleChannelSelect = (channelId: string) => {
  updateChannelState(channelId)
}

// 🔧 删除有问题的 getChannelConfig 函数
// 该函数混合了"获取"和"创建"职责，导致UI状态和数据库状态不一致

// 生成默认配置数据（基于Protocol3协议）
const generateDefaultConfigData = async (channelCode: string): Promise<Record<string, any>> => {
  try {
    // 使用协议适配器获取协议数据
    const protocolData = await getProtocolData(channelCode)

    if (!protocolData?.configSections) {
      return {}
    }

    const defaultData: Record<string, any> = {}

    // 遍历协议的配置分区
    protocolData.configSections.forEach((section: any) => {
      const sectionData: Record<string, any> = {}

      // 1. 从分区级别的默认值中提取
      if (section.defaultValues && typeof section.defaultValues === 'object') {
        Object.assign(sectionData, section.defaultValues)
      }

      // 2. 从字段中提取默认值
      if (section.fields && Array.isArray(section.fields)) {
        section.fields.forEach((field: any) => {
          if (field.defaultValue !== undefined && field.defaultValue !== null && field.defaultValue !== '') {
            sectionData[field.fieldKey] = field.defaultValue
          }
        })
      }

      // 3. 将分区数据添加到根对象
      if (Object.keys(sectionData).length > 0) {
        defaultData[section.sectionKey] = sectionData
      }
    })

    return defaultData

  } catch (error) {
    console.error(`生成默认配置数据失败: ${channelCode}`, error)
    return {}
  }
}

const getFieldSpan = (fieldType: string): number => {
  // 支持更多 Protocol3 字段类型
  const fullWidthFields = ['TEXTAREA', 'UPLOAD', 'JSON', 'CHECKBOX']
  return fullWidthFields.includes(fieldType) ? 24 : 12
}

const handleChannelToggle = async (channelId: string, enabled: boolean) => {
  if (!props.provider) return

  try {
    // 🔧 修复：直接从真实配置中查找，如果不存在就创建
    let config = currentProviderChannelConfigs.value.find(c => c.channelId === channelId)
    const template = state.channelTemplates.find(t => t.channelId === channelId)

    if (!template) {
      message.error('渠道模板未找到')
      return
    }

    // 如果配置不存在，先创建一个真实的配置对象
    if (!config) {
      const defaultConfigData = await generateDefaultConfigData(template.channelCode)
      config = {
        configId: `${state.currentProviderId}_${template.channelCode}_${Date.now()}`,
        providerId: state.currentProviderId,
        channelId: channelId,
        channelCode: template.channelCode,
        channelName: template.channelName,
        enabled: false,
        configData: defaultConfigData,
        status: 'INACTIVE',
        createdTime: new Date().toLocaleString(),
        updatedTime: new Date().toLocaleString()
      }

      // 添加到真实配置列表中
      const currentConfigs = getOrCreateProviderConfigs(state.currentProviderId)
      currentConfigs.push(config)
      state.dataVersion++
    }

    // 调用API更新状态
    await updateChannelStatus(props.provider.providerId, template.channelCode, enabled)

    // 更新本地状态
    config.enabled = enabled
    config.status = enabled ? 'ACTIVE' : 'INACTIVE'
    config.updatedTime = new Date().toLocaleString()

    // 如果启用了渠道且当前没有选中任何渠道，则选中这个渠道
    if (enabled && !state.selectedChannelId) {
      updateChannelState(channelId)
    }

    message.success(`渠道${enabled ? '启用' : '禁用'}成功`)
  } catch (error) {
    message.error(`渠道${enabled ? '启用' : '禁用'}失败`)
    console.error('渠道切换失败:', error)
  }
}

const handleFileUpload = (fieldKey: string, sectionKey: string, info: any) => {
  if (info.file.status === 'done') {
    setFieldValue(fieldKey, sectionKey, info.file.response?.url || info.file.name)
    message.success('文件上传成功')
  } else if (info.file.status === 'error') {
    message.error('文件上传失败')
  } else {
    // 预览模式，直接使用文件名
    setFieldValue(fieldKey, sectionKey, info.file.name)
    message.success(`文件 ${info.file.name} 已选择`)
  }
}

// 获取字段值（Protocol3分区结构）- 修复默认值支持
const getFieldValue = (fieldKey: string, sectionKey: string) => {
  const config = selectedChannelConfig.value
  if (!config) return ''

  // 1. 首先尝试从配置数据中获取已保存的值
  if (config.configData && config.configData[sectionKey] && config.configData[sectionKey][fieldKey] !== undefined) {
    const savedValue = config.configData[sectionKey][fieldKey]
    return savedValue
  }

  // 2. 如果没有已保存的值，尝试从协议中获取默认值
  const protocol = selectedChannelProtocol.value as any
  if (protocol?.configSections) {
    const section = protocol.configSections.find((s: any) => s.sectionKey === sectionKey)
    if (section?.fields) {
      const field = section.fields.find((f: any) => f.fieldKey === fieldKey)
      if (field && field.defaultValue !== undefined && field.defaultValue !== null && field.defaultValue !== '') {
        // 将默认值保存到配置数据中，避免重复计算
        if (!config.configData) {
          config.configData = {}
        }
        if (!config.configData[sectionKey]) {
          config.configData[sectionKey] = {}
        }
        config.configData[sectionKey][fieldKey] = field.defaultValue

        return field.defaultValue
      }
    }
  }

  // 3. 如果都没有，返回空值（根据字段类型返回合适的默认值）
  return ''
}

// 设置字段值（Protocol3分区结构）
const setFieldValue = (fieldKey: string, sectionKey: string, value: any) => {
  const config = selectedChannelConfig.value
  if (!config) return

  // 🔧 修复：确保 configData 存在
  if (!config.configData) {
    config.configData = {}
  }

  // 确保分区结构存在
  if (!config.configData[sectionKey]) {
    config.configData[sectionKey] = {}
  }

  // 设置分区中的字段值
  config.configData[sectionKey][fieldKey] = value
}

const handleSaveChannelConfig = async (channelId: string) => {
  if (!props.provider) return

  state.savingChannels.push(channelId)
  try {
    // 🔧 修复：从当前选中的配置中获取数据，这个配置可能是临时的
    const config = selectedChannelConfig.value
    const template = state.channelTemplates.find(t => t.channelId === channelId)

    if (!config || !template) {
      message.error('配置或渠道模板未找到')
      return
    }

    // 准备保存数据 - 使用后端生成ID，不再前端生成
    const saveData: ServiceProviderChannelConfigData = {
      configType: 1, // PROVIDER_CHANNEL
      ownerId: props.provider.providerId,
      ownerType: 1, // PROVIDER
      channelCode: template.channelCode,
      configData: JSON.stringify(config.configData || {}),
      enabled: config.enabled || false
    }

    // 调用统一渠道配置API保存（后端会自动生成ID）
    const response = await saveProviderChannelConfig(saveData)

    // 🔧 修复：保存成功后，确保配置在真实配置列表中
    let realConfig = currentProviderChannelConfigs.value.find(c => c.channelId === channelId)

    if (!realConfig) {
      // 如果之前没有真实配置，创建一个新的
      realConfig = {
        configId: response.data?.configId || '',
        providerId: state.currentProviderId,
        channelId: channelId,
        channelCode: template.channelCode,
        channelName: template.channelName,
        enabled: config.enabled || false,
        configData: config.configData || {},
        status: config.enabled ? 'ACTIVE' : 'INACTIVE',
        createdTime: new Date().toLocaleString(),
        updatedTime: new Date().toLocaleString()
      }

      // 添加到真实配置列表
      const currentConfigs = getOrCreateProviderConfigs(state.currentProviderId)
      currentConfigs.push(realConfig)
    } else {
      // 更新现有配置
      if (response.data?.configId) {
        realConfig.configId = response.data.configId
      }
      realConfig.configData = config.configData || {}
      realConfig.enabled = config.enabled || false
      realConfig.status = config.enabled ? 'ACTIVE' : 'INACTIVE'
      realConfig.updatedTime = new Date().toLocaleString()
    }

    state.dataVersion++

    message.success(response.message || '保存配置成功')
    emit('success')
  } catch (error) {
    console.error('保存配置失败:', error)
    message.error('保存配置失败: ' + (error as Error).message)
  } finally {
    state.savingChannels = state.savingChannels.filter(id => id !== channelId)
  }
}

// Protocol3 数据初始化
const initializeProtocol3Data = async () => {
  try {
    await initializeSampleData()
    state.protocol3Ready = true
  } catch (error) {
    console.error('Protocol3数据初始化失败:', error)
    throw error
  }
}

/**
 * 🔧 重构版本 - 加载服务商渠道配置
 * 核心修复：
 * 1. 严格的数据隔离和验证
 * 2. 使用Map存储避免数据串
 * 3. 详细的日志记录和错误处理
 * 4. 原子性操作保证
 */
const loadProviderChannelConfigs = async (providerId: string) => {
  state.loading = true
  state.error = null

  try {
    // 🔧 修复：确保当前服务商ID正确设置
    if (state.currentProviderId !== providerId) {
      state.currentProviderId = providerId
    }

    // 1. 🔑 关键：加载服务商已有的渠道配置（严格按服务商ID筛选）
    const response = await getProviderChannelConfigs({ providerId })

    if (!response.success) {
      throw new Error((response as any).error || '获取配置失败')
    }

    // 2. 加载渠道模板（全局共享，只需加载一次）
    if (state.channelTemplates.length === 0) {
      const configurableChannels = getAllConfigurableChannels()
      state.channelTemplates = configurableChannels.map(channel => ({
        channelId: channel.channelId,
        channelName: channel.channelName,
        channelCode: channel.channelCode,
        iconUrl: channel.iconUrl,
        description: channel.description || `${channel.channelName}支付接口配置`
      }))
    }

    // 3. 🔑 关键：严格验证和转换数据，确保数据隔离
    const validConfigs: ServiceProviderChannelConfig[] = []

    for (const apiConfig of response.data || []) {
      // 🔧 修复：严格验证数据归属
      if (apiConfig.ownerId !== providerId) {
        console.error(`数据归属错误! 配置 ${apiConfig.configId} 属于服务商 ${apiConfig.ownerId}，期望 ${providerId}`)
        continue // 跳过错误数据
      }

      if (apiConfig.ownerType !== 1 || apiConfig.configType !== 1) {
        console.warn(`配置类型错误! 配置 ${apiConfig.configId} 类型: ${apiConfig.configType}/${apiConfig.ownerType}`)
        continue // 跳过类型错误的数据
      }

      // 找到对应的渠道模板
      const template = state.channelTemplates.find(ch => ch.channelCode === apiConfig.channelCode)
      if (!template) {
        console.warn(`渠道模板不存在: ${apiConfig.channelCode}`)
        continue // 跳过无效渠道
      }

      // 转换为本地格式
      const localConfig: ServiceProviderChannelConfig = {
        configId: apiConfig.configId,
        providerId: apiConfig.ownerId, // 确保使用正确的服务商ID
        channelId: template.channelId,
        channelCode: apiConfig.channelCode,
        channelName: template.channelName,
        enabled: apiConfig.enabled || false,
        configData: typeof apiConfig.configData === 'string'
          ? JSON.parse(apiConfig.configData || '{}')
          : (apiConfig.configData || {}),
        status: (apiConfig.enabled || false) ? 'ACTIVE' : 'INACTIVE',
        createdTime: apiConfig.createdTime || new Date().toLocaleString(),
        updatedTime: apiConfig.updatedTime || new Date().toLocaleString()
      }

      validConfigs.push(localConfig)
    }

    // 4. 🔑 关键：使用数据隔离存储
    setProviderConfigs(providerId, validConfigs)

    // 5. 自动选择排序最前面的渠道（已配置的渠道优先，然后按渠道名称排序）
    if (!state.selectedChannelId && state.channelTemplates.length > 0) {
      // 使用排序后的渠道列表，选择第一个渠道
      const sortedTemplates = sortedChannelTemplates.value
      const firstChannelId = sortedTemplates.length > 0 ? sortedTemplates[0].channelId : ''

      if (firstChannelId) {
        updateChannelState(firstChannelId)
      }
    }

    state.initialized = true

  } catch (error) {
    const errorMsg = error instanceof Error ? error.message : '未知错误'
    console.error(`加载服务商 ${providerId} 配置失败:`, error)

    state.error = errorMsg
    message.error(`加载渠道配置失败: ${errorMsg}`)

    // 🔧 修复：错误时也要设置初始化状态，避免界面卡死
    state.initialized = true
  } finally {
    state.loading = false
  }
}

/**
 * 🔧 重构版本 - 完整的初始化流程
 * 核心修复：
 * 1. 服务商切换时的状态重置
 * 2. 数据隔离和缓存机制
 * 3. 错误处理和恢复
 * 4. 详细的日志记录
 */
const initializeModal = async () => {
  if (!props.provider) {
    return
  }

  const newProviderId = props.provider.providerId
  const isProviderChanged = state.currentProviderId !== newProviderId
  const hasExistingData = state.providerChannelConfigsMap.has(newProviderId)

  // 🔑 关键：服务商切换时重置状态
  if (isProviderChanged) {
    resetForNewProvider(newProviderId)
  }

  // 如果已有缓存数据且Protocol3已就绪，直接使用缓存
  if (hasExistingData && state.protocol3Ready && !isProviderChanged) {
    state.initialized = true

    // 恢复选中状态
    const configs = currentProviderChannelConfigs.value
    if (!state.selectedChannelId && configs.length > 0) {
      const firstEnabled = configs.find(c => c.enabled)
      const firstChannelId = firstEnabled?.channelId || state.channelTemplates[0]?.channelId
      if (firstChannelId) {
        updateChannelState(firstChannelId)
      }
    }
    return
  }

  state.loading = true
  try {
    // 1. 🔧 修复：确保Protocol3数据只初始化一次
    if (!state.protocol3Ready) {
      await initializeProtocol3Data()
    }

    // 2. 🔑 关键：加载服务商渠道配置（带数据隔离）
    await loadProviderChannelConfigs(newProviderId)

  } catch (error) {
    console.error('模态框初始化失败:', error)
    message.error('初始化失败: ' + (error as Error).message)
  } finally {
    state.loading = false
  }
}

// 🔧 重构版本 - 监听器
// 核心修复：正确的服务商切换和状态管理

/**
 * 监听服务商变化 - 关键的数据隔离逻辑
 */
watch(
  () => props.provider,
  async (newProvider, oldProvider) => {
    if (!newProvider) {
      return
    }

    const newProviderId = newProvider.providerId
    const oldProviderId = oldProvider?.providerId
    const isProviderChanged = oldProviderId && newProviderId !== oldProviderId

    if (props.visible) {
      if (isProviderChanged) {
        // 🔑 关键：使用新的重置机制
        resetForNewProvider(newProviderId)
      }

      // 初始化新服务商的数据
      await initializeModal()
    }
  },
  { immediate: true }
)

/**
 * 监听模态框显示状态变化
 */
watch(
  () => props.visible,
  async (visible, wasVisible) => {
    if (visible && props.provider) {
      await initializeModal()
    } else if (!visible) {
      resetState()
    }
  }
)
</script>

<style scoped>
/* 渠道配置工作区样式 */
.channel-config-modal :deep(.ant-modal-body) {
  padding: 0;
}

.channel-config-workspace {
  display: flex;
  height: 92vh;
  min-height: 800px;
  max-height: 1000px;
}

.channel-sidebar {
  width: 320px;
  border-right: 1px solid #f0f0f0;
  background: #fafafa;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.channel-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.channel-item {
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  margin-bottom: 8px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.channel-item:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
}

.channel-item.active {
  border-color: #1890ff;
  background: #e6f7ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
}

.channel-item.configured {
  border-left: 4px solid #52c41a;
}

.channel-item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.channel-basic {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.channel-icon {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  object-fit: cover;
}

.channel-info {
  flex: 1;
}

.channel-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 2px;
}

.channel-status {
  margin-left: 8px;
}

.channel-detail {
  flex: 1;
  background: #fff;
  display: flex;
  flex-direction: column;
}

.loading-state,
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background: #fafafa;
}

.channel-detail-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.detail-header {
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
  background: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.channel-title {
  display: flex;
  align-items: center;
  gap: 16px;
}

.channel-title .channel-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
}

.channel-title h3 {
  margin: 0 0 4px 0;
  font-size: 18px;
  color: #333;
}

.channel-desc {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.config-form-container {
  flex: 1;
  padding: 20px 24px;
  overflow-y: auto;
  background: #fafafa;
}

.config-tabs :deep(.ant-tabs-content-holder) {
  padding: 0;
}

.fixed-save-button {
  position: absolute;
  bottom: 24px;
  right: 24px;
  z-index: 100;
}
</style>